import axios from 'axios'
import {Message} from 'element-ui'

import {setUpLoading, uninstallLoading} from '@/utils/request/req.inter.loading'
import {setUpParse} from '@/utils/request/req.inter.parse'
import {setUpToken} from '@/utils/request/req.inter.token'

const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 6e4 // 请求超时一分钟
})

service.interceptors.request.use(
  config => {
    setUpLoading(config)

    const withTokenConfig = setUpToken(config)
    
    return setUpParse(withTokenConfig)
  },
  error => Promise.reject(error)
)

service.interceptors.response.use(
  (responseData) => {
    uninstallLoading()
    let data = responseData.data

    if (data.code && data.code !== 200) {
      Message({
        message: data.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      })
    }else if(data.code === 0) {
      Message({
        message: data.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return data
  },
  error => {
    uninstallLoading()

    Message({
      message: '网络错误！',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
